from django.shortcuts import render
from django.http import HttpResponse
import json
import datetime
import os
import requests
# Create your views here.

def getText(request):
	if request.method == 'POST' :
		# print("the POST method")
		# concat = request.POST
		postBody = request.body
		# print(concat)
		# print(type(postBody))
		# print(postBody)
		json_result = json.loads(postBody)
		
		print(json_result)
		# if request.method=='GET':
		# 	ID=request.GET.get('id',default='110')
		# 	s_id=request.GET.get('s_id',default='111')
		# 	print(ID)
		# 	print(s_id)
		data={
			'session_id': json_result['sessionId'],
			'type': 'text',
			'data': '你好，请再次输入您的问题',
			'addend':{
				'session_id':json_result['sessionId'],
				'type':json_result['data'],
				'data':json_result['data']
			}
		}
		return HttpResponse(json.dumps(data), content_type="application/json")

def getRecord(request):
	if request.method == 'POST':
		#print(request.body)
		#sessionId = request.POST.get('sessionId')
		json_result = request.POST
		#json_result = json.loads(json_result)
		print(json_result)
		#print(sessionId)
		#postBody = request.body
		#json_result = json.loads(postBody)
		file = request.FILES.get('file',None)
		with open(file.name,"wb") as f:
			for chunk in file.chunks():
				f.write(chunk)
		data={
			'session_id': json_result['sessionId'],
			'type': 'text',
			'data': '你好，已收到您的语音',
		}
		return HttpResponse(json.dumps(data, ensure_ascii = False), content_type="application/json")
		# return HttpResponse("file upload success!")
		#if file:
		#	day_dir = datetime.datetime.now().strftime('%Y%m%d')
		#	pre_dir = os.path.join('./data/',day_dir)
		#	if not os.path.exists(pre_dir):
		#		os.mkdir(pre_dir)
		#	filename=os.path.join(pre_dir,file.name)
		#	with open(filename,'wb') as f:
		#		for line in file.chunks():
		#			f.write(line)
		#	return HttpResponse('上传成功')
	else:
		return HttpResponse('上传失败')

def onLogin(request):
	if request.method == 'GET':
		#return HttpResponse("oook")
		code = request.GET.get('code')
		url = "https://api.weixin.qq.com/sns/jscode2session"
		params = {
			"appid":"wxe976181001e934f8",
			"secret":"3bfb18ceee7bc1527a4b756b9e456e8f",
			"js_code":code,
			"grant_type":"authorization_code"
		}
		res = requests.get(url = url, params = params)
		# print(json.load(res))
		data = {
			'openid': res.json()['openid']
		}
		return HttpResponse(json.dumps(data), content_type="application/json")
	else:	
		return HttpResponse("err")

